<template>
  <div>
    <el-card>
      <div class="noptice-header flex items-center justify-between">
        <el-button type="primary" size="small" @click="createClick"
          >新增</el-button
        >
        <el-button type="primary" size="small" @click="getData">
          <el-icon>
            <Refresh />
          </el-icon>
        </el-button>
      </div>
      <el-table :data="tableList">
        <el-table-column prop="name" label="角色名称"></el-table-column>
        <el-table-column
          prop="desc"
          label="角色描述"
          width="280"
        ></el-table-column>
        <el-table-column label="状态" width="280">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              @change="statusChange(row)"
              :active-value="1"
              :inactive-value="0"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              text
              type="primary"
              size="small"
              @click="permissionsClick(scope.row)"
              >配置权限</el-button
            >
            <el-button
              text
              type="primary"
              size="small"
              @click="editNoticeClick(scope.row)"
              >修改</el-button
            >
            <el-popconfirm
              title="是否要删除该角色？"
              confirmButtonText="确认"
              cancelButtonText="取消"
              @confirm="handleDelete(scope.row.id)"
            >
              <template #reference>
                <el-button text type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="flex items-center justify-center mt-3">
        <el-pagination
          background
          layout="prev, pager,next"
          :total="total"
          :current-page="page"
          :page-size="limit"
          @current-change="changePage"
        />
      </div>
    </el-card>

    <Drawer
      ref="DrawerRef"
      :title="title === 'add' ? '添加公告' : '修改公告'"
      @submit="submit"
    >
      <el-form
        ref="formRef"
        :model="fromData"
        label-width="100px"
        :rules="rules"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="fromData.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="desc">
          <el-input
            v-model="fromData.desc"
            placeholder="请输入角色描述"
            type="textarea"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色状态" prop="status">
          <el-switch
            v-model="fromData.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
    </Drawer>
    <!-- 
        :check-strictly="checkStrictly"
在显示复选框的情况下，是否严格的遵循父子不互相关联的做法，默认为 false
     -->
    <Drawer ref="permissionsDrawer" @submit="treeSubmit">
      <el-tree-v2
        :check-strictly="checkStrictly"
        ref="elTreeRef"
        node-key="id"
        :default-expanded-keys="defaultExpandedKeys"
        :data="ruleList"
        :props="{ label: 'name', children: 'child' }"
        show-checkbox
        :height="treeHeight"
        @check="handleTreeCheck"
      >
        <template #default="{ node, data }">
          <div class="flex items-center">
            <el-tag :type="data.menu ? '' : 'info'" size="small">
              {{ data.menu ? "菜单" : "权限" }}
            </el-tag>
            <span class="ml-2 text-sm"> {{ data.name }} </span>
          </div>
        </template>
      </el-tree-v2>
    </Drawer>
  </div>
</template>

<script setup>
import { ref } from "vue";
import Drawer from "@/components/Drawer/index.vue";
import {
  getRoleList,
  changStatus,
  addRole,
  editRole,
  delRole,
  setRole,
} from "@/api/role";
import { getRuleList } from "@/api/rule";
import { useInitTable, useInitForm } from "@/composables/useCommon.js";
import { Toast } from "@/utils/utils";
const {
  tableList,
  page,
  total,
  limit,
  getData,
  changePage,
  handleDelete,
  statusChange,
} = useInitTable({
  getList: getRoleList,
  del: delRole,
  status: changStatus,
});

const {
  fromData,
  title,
  formRef,
  rules,
  DrawerRef,
  createClick,
  submit,
  editNoticeClick,
} = useInitForm({
  fromData: {
    name: "",
    status: 1,
    desc: "",
  },
  create: addRole,
  updata: editRole,
  getData: getData,
  // rules: {
  //   title: [{ required: true, message: "请输入公告标题", trigger: "blur" }],
  //   content: [{ required: true, message: "请输入公告内容", trigger: "blur" }],
  // },
});
// 权限配置
const permissionsDrawer = ref(null);
let ruleList = ref([]);
let treeHeight = ref(0);
let defaultExpandedKeys = ref([]); // 默认展开第一层数据
let currentId = ref(""); // 要修改的角色id
// 当前角色的权限id
let ruleIds = ref([]);
let elTreeRef = ref(null);
let checkStrictly = ref(false);
const permissionsClick = (row) => {
  currentId.value = row.id;
  // 获取到修改的id
  getRuleList().then((res) => {
    checkStrictly.value = true;
    ruleList.value = res.data.list;
    defaultExpandedKeys.value = res.data.list.map((o) => o.id);
    treeHeight.value = window.innerHeight - 200;
    permissionsDrawer.value.openDrawer();
    // 当前角色拥有的权限ID
    ruleIds.value = row.rules.map((o) => o.id);
    setTimeout(() => {
      elTreeRef.value.setCheckedKeys(ruleIds.value);
      checkStrictly.value = false;
    }, 150);
  });
};
// 选中的值
const handleTreeCheck = (...e) => {
  ruleIds.value = [...e[1].checkedKeys, ...e[1].halfCheckedKeys];
};
// 提交的时候
const treeSubmit = () => {
  setRole({ id: currentId.value, rule_ids: ruleIds.value }).then((res) => {
    if (res.data) {
      Toast("分配权限成功");
      permissionsDrawer.value.closeDrawer();
      getData();
    }
  });
};
</script>
